package main

import (
	"crypto/hmac"
	"crypto/sha256"
	"crypto/tls"
	"encoding/hex"
	"log"
	"time"

	"gitee.com/haoyupei/mqttgw"
	mqtt "github.com/eclipse/paho.mqtt.golang"
)

const (
	virtualTime = "2020051211"
	address     = "121.36.42.100"
	port        = 1883
)

func tlsCert() *tls.Config {

	cert, err := tls.LoadX509KeyPair("../certsample/mqtt.crt", "../certsample/mqtt.key")
	if err != nil {
		log.Println(err)
	}

	return &tls.Config{
		ClientAuth:         tls.NoClientCert,
		ClientCAs:          nil,
		Certificates:       []tls.Certificate{cert},
		InsecureSkipVerify: true,
	}

}

type info struct {
	deviceid, secret string
}

func (i info) clientID() string {
	return i.deviceid + "_" + "0" + "_" + "0" + "_" + virtualTime
}

func (i info) username() string {
	return i.deviceid
}
func (i info) password() string {
	hmac256 := hmac.New(sha256.New, []byte(virtualTime))
	hmac256.Write([]byte(i.secret))
	return hex.EncodeToString(hmac256.Sum(nil))
}

func (i info) debug() {
	log.Println(i.clientID(), i.username(), i.password())
}
func main() {

	cont := &info{"5ea453534398a903b52d32bb_certmqtt", "A6A57CE948A2FBB0719AF04742F592A8C4C0214F2B76C77CAD185933ADA67E00"}

	//cont.debug()

	mmsg := make(chan mqtt.Message, 100)

	cfg := mqtt.NewClientOptions()

	cfg.SetUsername(cont.username())
	cfg.SetClientID(cont.clientID())
	//	cfg.SetPassword(cont.password())
	cfg.AddBroker("ssl://iot-mqtts.cn-north-4.myhuaweicloud.com:8883")
	cfg.SetKeepAlive(50 * time.Second)
	cfg.SetTLSConfig(tlsCert())
	cfg.SetDefaultPublishHandler(func(cli mqtt.Client, msg mqtt.Message) {
		mmsg <- msg
	})

	cli := mqtt.NewClient(cfg)

	if tk := cli.Connect(); tk.Wait() && tk.Error() != nil {
		log.Fatal("123", tk.Error())
	}
	log.Println("ok")

	topic := mqttgw.NewTopic(cont.deviceid)

	//订阅消息
	if tk := cli.Subscribe(topic.SubDeviceEvent(), 1, func(cli mqtt.Client, msg mqtt.Message) {

		log.Println(string(msg.Payload()), msg.Topic())
	}); tk.Wait() && tk.Error() != nil {
		log.Println("subs err: ", tk.Error())
	}

	defer cli.Disconnect(100)

	go func() {
		sample := []byte(`{"devices":[{"device_id":"5ea453534398a903b52d32bb_123","services":[{"service_id":"A001","properties":{"High":"1"}}]}]}`)
		for range []byte{99: 0} {
			if tk := cli.Publish(topic.SubDevicePropertiesReport(), 1, false, sample); tk.Wait() && tk.Error() != nil {
				log.Println(tk.Error())
			}
			time.Sleep(7 * time.Second)
		}

	}()

	for {
		select {
		case msg := <-mmsg:
			{
				log.Println(string(msg.Topic()), string(msg.Payload()))
			}
		}
	}

	// var gp sync.WaitGroup

	// gp.Add(100)

	// go func() {
	// 	for i := range []byte{99: 0} {
	// 		if tk := cli.Publish(topic.SubDevicePropertiesReport("5ea453534398a903b52d32bb_1234"), 1, false, []byte{1, byte(i)}); tk.Wait() && tk.Error() != nil {
	// 			log.Println(tk.Error())
	// 		}
	// 		time.Sleep(7 * time.Second)
	// 		gp.Done()
	// 	}

	// }()

	// //	log.Println("connet success")

	// gp.Wait()

}
